﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native)]
public struct Recta : INullable {

    private static readonly Regex regExpr = new Regex(@"(\((?<x1>[0-9]+)\,(?<y1>[0-9]+)\)\-\((?<x2>[0-9]+)\,(?<y2>[0-9]+)\))");

    public override string ToString() { return "Start: (" + x1 + ", " + y1 + ") - End: (" + x2 + ", " + y2 + ")"; }

    public bool IsNull {
        get { return Comprimento == 0; }
    }

    public static Recta Null {
        get {
            Recta r = new Recta();
            return r;
        }
    }

    public int x1 { get; set; }
    public int x2 { get; set; }
    public int y1 { get; set; }
    public int y2 { get; set; }

    public static Recta Parse(SqlString s) {
        if (s.IsNull || s.Value.ToLower().Equals("null"))
            return Null;
        if (!regExpr.IsMatch(s.Value))
            throw new ApplicationException("Invalid Format");
        Match m = regExpr.Match(s.Value);
        Recta u = new Recta();
        u.x1 = Int32.Parse(m.Result("${x1}"));
        u.y1 = Int32.Parse(m.Result("${y1}"));
        u.x2 = Int32.Parse(m.Result("${x2}"));
        u.y2 = Int32.Parse(m.Result("${y2}"));
        return u;
    }

    public double Comprimento {
        get {
            return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
        }
    }
}